package com.example.vote.service;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.vote.bean.*;
import com.example.vote.mapper.*;
import com.example.vote.utils.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.LinkedList;
import java.util.List;

@Service
public class TVoteServiceImpl extends ServiceImpl<TVoteDao, TVote> {

    @Autowired
    TItemDao itemDao;
    @Autowired
    TItemVoteServiceImpl itemVoteService;
    @Autowired
    UserDao userDao;

    @Autowired
    TItemVoteSubService itemVoteSubService;
    @Autowired
    UserVoteServiceImpl userVoteService;
    @Autowired
    ScoreContentService scoreContentService;


    @Transactional
    public Result vote(FormSignVo formSignVo) {
        TItemVote itemVote = formSignVo.getItemVote();
        List<TItemVoteSub> itemVoteSubs = formSignVo.getItemVoteSubs();
        if (ObjectUtils.isEmpty(itemVote) || ObjectUtils.isEmpty(itemVoteSubs)) {
            return Result.error("投票信息不完整");
        }
        // 检查候选人是否已经投完
        long voteCount = this.count(new LambdaQueryWrapper<>(TVote.class)
                .eq(TVote::getItemId, itemVote.getItemId()));
        long scoreCount = scoreContentService.count(new LambdaQueryWrapper<>(ScoreContent.class)
                .eq(ScoreContent::getItemId, itemVote.getItemId()));
        if (itemVoteSubs.size() != voteCount * scoreCount) {
            return Result.error("投票数量不正确");
        }
        User user = (User) StpUtil.getSession().get("user");
        itemVote.setPhone(user.getPhone());
        itemVote.setName(user.getName());
        itemVoteService.save(itemVote);
        for (TItemVoteSub itemVoteSub : itemVoteSubs) {
            itemVoteSub.setPhone(user.getPhone());
            itemVoteSub.setName(user.getName());
        }
        itemVoteSubService.saveBatch(itemVoteSubs);
        return Result.success(null, "投票成功");
    }
}
